const express = require('express');
const router = express.Router();
const path = require("path");

const PagerHelper = require("../util/PagerHelper.js");
//分页插件
const pager = PagerHelper.pagerHelper;
pager.href = "/api/book/list.do";
console.log(pager);

// const dao = require("../model/mongodb/BookDao");
const dao = require("../model/mysql/BookDao");

let searchArgs;//保存搜索的参数

router.get("/list.do", async (req, res, next) => {
    //调用Promise API时，因为会在异步函数中触发错误，这类错误是app.js配置的错误中间件无法处理的
    // let where = {};//查询条件对象，mongdb的写法
    let where = "";
    let flag = 0;//控制多条件是否要加and
    if (searchArgs) {
        console.log("searchArgs", searchArgs);
        if (searchArgs.name) {
            if (where.trim().length === 0) {
                where += "where ";
            }
            where += `name like '%${searchArgs.name}%' `;
            flag++;
            // where.name = RegExp(searchArgs.name, "i");
        }
        if (searchArgs.minPrice) {
            // if (!where.price) {
            //     where.price = {};
            // }
            // where.price.$gte = searchArgs.minPrice
            if (where.trim().length === 0) {
                where += "where ";
            }
            if (flag > 0) {
                where += " and "
            }
            where += ` price >= ${searchArgs.minPrice} `;
            flag++;
        }
        if (searchArgs.maxPrice) {
            // if (!where.price) {
            //     where.price = {};
            // }
            // where.price.$lte = searchArgs.maxPrice
            if (where.trim().length === 0) {
                where += "where ";
            }
            if (flag > 0) {
                where += " and "
            }
            where += `price <= ${searchArgs.maxPrice}`;
            flag++;
        }
        console.log(where);
    }
    //
    dao.getCount(where).then(count => {
        console.log("count", count);
        pager.setCount(count);
        return dao.findByPage(where);
    }).then(data => {
        console.log("data", data);
        res.json({
            title: "书本购物车",
            books: data,
            pager
        });
    }).catch(err => next(err));
});

router.get("/list.html", (req, res, next) => {
    res.sendFile(path.join(__dirname, "../views/api/book/list.html"));
});

/**
 * 搜索功能
 */
router.post("/list.do", (req, res, next) => {
    console.log(req.body);
    if (req.body) {
        searchArgs = {};
        if (req.body.name && req.body.name.trim().length > 0) {
            searchArgs.name = req.body.name
        } else {
            delete searchArgs.name;
        }
        if (req.body.minPrice && req.body.minPrice.trim().length > 0) {
            searchArgs.minPrice = parseFloat(req.body.minPrice);
        } else {
            delete searchArgs.minPrice;
        }
        if (req.body.maxPrice && req.body.maxPrice.trim().length > 0) {
            searchArgs.maxPrice = parseFloat(req.body.maxPrice);
        } else {
            delete searchArgs.maxPrice;
        }
    }
    res.redirect("/api/book/list.do");
})

router.get("/del.do", (req, res, next) => {
    // lodash.remove(books, value => value.id == req.query.id);
    if (req.query.id) {
        dao.deleteById(req.query.id).then(data => res.redirect("/book/list.html")).catch(err => next(err));
    } else {
        res.redirect("/book/list.html");
    }
});
router.get("/delBatch.do", (req, res, next) => {
    let idsStr = req.query.ids;
    console.log(idsStr);
    let ids = idsStr.split(",");//得到的是一个字符串数组
    // lodash.remove(books, value => ids.some(id => id == value.id));
    dao.deleteByIds(ids).then(data => res.redirect("/book/list.html")).catch(err => next(err));
});
router.get("/add.html", (req, res) => {
    res.render("book/add", {
        title: "添加书本"
    })
});
router.get("/edit.html", (req, res, next) => {
    let {id} = req.query;
    if (id) {
        // let editObj = books.find(value => value.id == id);
        dao.findById(id).then(editObj => {
            if (editObj) {
                res.render("book/add", {
                    title: "添加书本",
                    editObj
                });
            } else {
                res.redirect("/book/list.html");
            }
        }).catch(err => next(err));

    } else {
        res.redirect("/book/list.html");
    }

});
router.post("/save.do", (req, res, next) => {
    let newObj = Object.assign({}, req.body);
    //区分添加还是编辑
    if (newObj.id) {
        //编辑
        // let editObj = books.find(value => value.id == newObj.id);
        // //引用数据类型的特点
        // Object.assign(editObj, newObj);
        dao.update(newObj, newObj.id).then(data => res.redirect("/book/list.html")).catch(err => next(err));
    } else {
        //添加
        // // books.pop();删除最后一个元素
        // newObj.id = lodash.last(books).id + 1;
        // //保存到数组中
        // books.push(newObj);
        newObj.id = 0;//id是自动增长，必须是0值
        dao.insert(newObj).then(data => res.redirect("/book/list.html")).catch(err => next(err));
    }
});

// router.get("/toInsertSql", (req, res, next) => {
//     dao.findAll().then(data => {
//         console.log(data[0].name);
//         let sqls = [];
//         for (let i = 0; i < data.length; i++) {
//             let item = data[i];
//             let sql = "insert into books(name, price, count, createDate) values(";
//             sql += `'${item.name}', '${item.price}', '${item.count}', '${res.app.locals.moment(item.createDate).format("yyyy-MM-DD")}');`;
//             sqls.push(sql);
//         }
//         console.log(sqls.join("\n"));
//         res.setHeader("Context-Type", "html/text");
//         res.send(sqls.join("\n"));
//     }).catch(err => next(err));
// });

module.exports = router;
